package com.tozed.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;

import com.tozed.test.R;
import com.tozed.util.BitmapUtils;

public class MetroButton extends ImageView
{
	private final static String TAG = "MetroButton";
	
	private Bitmap mBmpFinger;
	private Bitmap mBmpIndicator;
	private Bitmap mBmpLabelNew;
	private int mState = 0; // 按下

	private int mColorId;
	private float mTextSize;
	private boolean mIsBig;
	private boolean mIsNewFlag;
	private int mIndex;
	private String mText;
	
	private int mTextX,mTextY;

	private int screenW;
	private int screenH;
	
	private Drawable mDrawable = null;
	private int mDrawableWidth;
    private int mDrawableHeight;
    
    private Context mContext;

	//public interface onClickListener{
	//	public void onClick();
	//}
	
	private android.view.View.OnClickListener mListener = null;

	private int[] mColors = { 
			getResources().getColor(R.color.red),
			getResources().getColor(R.color.orange),
			getResources().getColor(R.color.blue),
			getResources().getColor(R.color.purple),
			getResources().getColor(R.color.air),
			getResources().getColor(R.color.texi),
			getResources().getColor(R.color.jingdian) };

	private Bitmap[] mBitmaps = {
			BitmapFactory.decodeResource(getResources(), R.drawable.ic_default),
	};

	public MetroButton(Context context){
		super(context);
		mContext = context;
	}

	public MetroButton(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		mContext = context;
		
		mBmpFinger = BitmapUtils.zoomImage(BitmapFactory.decodeResource(
						getResources(), R.drawable.fingerprint), 127, 122);

		mBmpLabelNew = BitmapFactory.decodeResource(getResources(),R.drawable.label_new);
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MetroButton);
		
		mColorId    = a.getInt(R.styleable.MetroButton_bgcolor, 0);
		mTextSize = a.getDimension(R.styleable.MetroButton_textSize, 24);
		mIsBig 	 = a.getBoolean(R.styleable.MetroButton_big, true);
		mIndex     = a.getInt(R.styleable.MetroButton_index, 0);
		mIsNewFlag = a.getBoolean(R.styleable.MetroButton_newflag, false);
		mText     = a.getString(R.styleable.MetroButton_text);
		
		mDrawable = a.getDrawable(R.styleable.MetroButton_icon);
		if (mDrawable != null){
			mBmpIndicator = drawable2Bitmap(mDrawable);
		}else{
			mBmpIndicator = mBitmaps[mIndex];
		}
		
		if (mBmpIndicator == null){
			mBmpIndicator = mBitmaps[0];
		}
		
		//Log.d(TAG, "color:" + mColorId + " textsize:" + mTextSize + " big:" + mIsBig + " home:" + mIndex);
		
		// 获取屏幕的大小
		screenW = ((Activity) context).getWindow().getWindowManager()
				.getDefaultDisplay().getWidth() / 2 - 16;
		
		if (mIsBig){
			screenH = screenW;
		} else{
			screenH = screenW/2 - 4;
		}
		
		a.recycle();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		// 重新设置屏幕大小
		setMeasuredDimension(screenW, screenH);
	}

	/*
	 * orange 2182F7 light red 7359EF 約1�7 B551A5 Blue CE8A39 air CEBE00 texi
	 * 9CAA00  00AA73
	 */

	// 这里计算大小不要用cnavas的大小来计算，会出错，因为真机以模拟器中得到的大小不一样
	@Override
	protected void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);

		canvas.drawColor(mColors[mColorId]);
		Paint paint = new Paint();
		paint.setColor(Color.WHITE);
		//paint.setTextSize(24);
		paint.setTextSize(mTextSize);
		
		
		if(mIsBig){
			Matrix matrix = new Matrix();
			matrix.postTranslate(this.getWidth() / 2 - mBmpIndicator.getWidth()
					/ 2, this.getHeight() / 2 - mBmpIndicator.getHeight() / 2);
			
			mTextX = 20;
			mTextY = 50;
			
			if (mText != null)
				canvas.drawText(mText, mTextX, mTextY, paint);
			canvas.drawBitmap(mBmpIndicator, matrix, paint);
		}else{
			// draw icon bmp
			Matrix matrix_small = new Matrix();
			matrix_small.postTranslate(10, this.getHeight()/2 - mBmpIndicator.getHeight()/2);
			canvas.drawBitmap(mBmpIndicator, matrix_small, new Paint());
			
			mTextX = mBmpIndicator.getWidth() + 20;
			mTextY = this.getHeight()/2 + mBmpIndicator.getHeight()/2 - 15;
			
			// draw text
			if (mText != null)
				canvas.drawText(mText, mTextX, mTextY, paint);
			
			if (mIsNewFlag){
				Matrix matrix_new = new Matrix();
				matrix_new.postTranslate(screenW - mBmpLabelNew.getWidth(), 0);
				canvas.drawBitmap(mBmpLabelNew, matrix_new, new Paint());
			}
		}
		
		// draw finger bmp
		if (mState == 1){
			Matrix matrix2 = new Matrix();
			matrix2.postTranslate(this.getWidth()/2 - mBmpFinger.getWidth()/2,
					this.getHeight()/2 - mBmpFinger.getHeight()/2);
			canvas.drawBitmap(mBmpFinger, matrix2, new Paint());
		}
	}
	
	public void setIconDrawable(Drawable drawable)
	{
		if (drawable == null)
			return;
		
		if (mDrawable != drawable){
			final int oldWidth = mDrawableWidth;
			final int oldHeight = mDrawableHeight;

			mDrawable = drawable;
			mBmpIndicator = drawable2Bitmap(mDrawable);

			if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight){
				requestLayout();
			}
			invalidate();
		}
	}
	
	public void setText(int resId){
		String str = mContext.getString(resId);
		mText = str;
		
		requestLayout();
		invalidate();
	}
	
	public void setText(String str){
		if (mText != str){
			mText = str;
			requestLayout();
			invalidate();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		float start = 1.0f;
		float end = 0.95f;
		Animation scaleAnimation = new ScaleAnimation(start, end, start, end,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		
		Animation endAnimation = new ScaleAnimation(end, start, end, start,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		
		scaleAnimation.setDuration(200);
		scaleAnimation.setFillAfter(true);
		endAnimation.setDuration(200);
		endAnimation.setFillAfter(true);
		
		switch (event.getAction())
		{
		case MotionEvent.ACTION_DOWN:
			this.startAnimation(scaleAnimation);
			mState = 1;
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
			this.startAnimation(endAnimation);
			mState = 0;
			invalidate();
			if (mListener != null){
				mListener.onClick(this);
			}
			break;
		// 滑动出去不会调用action_up,调用action_cancel
		case MotionEvent.ACTION_CANCEL:
			this.startAnimation(endAnimation);
			mState = 0;
			invalidate();
			break;
		}
		
		// 不返回true，Action_up就响应不了
		return true;
	}

	//public void setOnClickListener(onClickListener l)
	//{
	//	this.mListener = l;
	//}
	
	@Override
	public void setOnClickListener(OnClickListener l)
	{
		// TODO Auto-generated method stub
		// super.setOnClickListener(l);
		
		this.mListener = l;
	}
	
	private Bitmap drawable2Bitmap(Drawable drawable) 
	{  
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();  
        } else if (drawable instanceof NinePatchDrawable) {  
            Bitmap bitmap = Bitmap.createBitmap(  
                            drawable.getIntrinsicWidth(),  
                            drawable.getIntrinsicHeight(),  
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);  
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),  
                    drawable.getIntrinsicHeight());  
            drawable.draw(canvas);  
            return bitmap;  
        } else {  
            return null;  
        }  
    }  
}
